package com.sbl.bajw.pc.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sbl.bajw.common.DbManager;
import com.sbl.bajw.common.MyBatisDao;
import com.sbl.bajw.common.web.MessageException;
import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.common.web.SessionUnit;
import com.sbl.bajw.common.web.WebContext;
import com.sbl.bajw.mapper.UserDao;
import com.sbl.bajw.pc.model.UserGpsModel;
import com.sbl.bajw.pc.model.UserModel;
import com.sbl.bajw.util.FileUpload;
import com.sbl.bajw.util.LogUtil;

@Service
public class UserService {
	
	@Resource
	private UserDao dao;
	
	@Resource
	private JWTTallGroupService jwtTallGroupService;
	
	static HashMap<String,UserGpsModel> userGpsModelMap = new HashMap<String, UserGpsModel>();

	static Logger log;
	
	static Logger gpsLog = null;
	
	static{
		log = LogUtil.getLogger("userlog");
	}
	
	static{
		gpsLog = LogUtil.getLogger("gpsLog");
	}
	
	@Resource 
	private MyBatisDao gridDao;
	
	/**
	 * @作者：罗琦
	 * @return 获取用户GPS接口（APP）
	 */
	public List<HashMap<String, Object>> getUserGpsList(){
		List<HashMap<String, Object>> list= dao.getUserGpsList();
		return list;
	}
	
	public UserModel getModelByName(String username){
		if(username == null || username.equals("") )
		{
			return null;
		}
		UserModel model = dao.getModelByName(username);
		return model;
	}
	
	public void update(UserModel user){
		dao.update(user);
	}
	
	public UserModel getModel(String id){
		UserModel model = dao.getModel(id);
		return model;
	}
	
	public UserModel getModelWithGpsInfo(String id){
		HashMap<String, String> parm = new HashMap<String, String>();
		parm.put("userid", id);
		UserModel model = dao.getModelWithGpsInfo(id);
		return model;
	}
	
	public HashMap<String, Object> getUserModelApp(String id){
		HashMap<String, Object> list = dao.getUserModelApp(id);
		return list;
	}
	
	public UserModel getUserModel(String id){
		UserModel user = dao.getUserModel(id);
		return user;
	}
	
	public String getExtensionMaterialize(HashMap<String, Object> parm){
		String result = gridDao.selectPage(UserDao.class, parm, "getExtensionMaterialize");
		return result;
	}
	
	public UserModel createModel(String username,String password){
		UserModel model = new UserModel();
		String id = dao.getId();
		model.setId(id);
		model.setUsername(username);
		model.setPassword(password);
		model.setImageurl("images/nohead.png");
		dao.insert(model);
		return model;
	}
	
	public void updateUserGps(UserModel model){
		UserGpsModel userGpsModel = getUserGpsModel(model.getId());
		userGpsModel.add(model.getGpsX(), model.getGpsY(),model.getGpsSpeed());
		if(model.getGpsX() < 10 || model.getGpsY() < 10 ){
			model.setGpsX(null);
			model.setGpsY(null);
		}
		dao.update(model);
		if(userGpsModel.getGpsCount() > 5){
			dao.insertUserGps(userGpsModel);
			userGpsModel.clear();
			gpsLog.info(userGpsModel.getUserid()+" gps数据入库");
		}
	}
	
	public String getUserEasyList(HashMap<String, Object> parm){
		String list = gridDao.selectPage(UserDao.class, parm, "getEasyList");
		return list;
	}
	
	public String getUserList(HashMap<String, Object> parm){
		String list = gridDao.selectPage(UserDao.class, parm, "getModelList");
		return list;
	}
	
	public List<HashMap<String, Object>> getModelList(HashMap<String, Object> parm){
		List<HashMap<String, Object>> list = dao.getModelList(parm);
		return list;
	}
	
	public String getLocalhostModelList(HashMap<String, Object> parm){
		String list = gridDao.selectPage(UserDao.class, parm, "getLocalhostModelList");
		return list;
	}
	
	public List<HashMap<String, String>> getModelsForMap(HashMap<String, String> parm){
		List<HashMap<String, String>> list = dao.getModelsForMap(parm);
		return list;
	}
	
	public HashMap<String, Object> getCount(){
		HashMap<String, Object> map = dao.getCount();
		return map;
	}
	
	public void insertUserGps(UserGpsModel model){
		dao.insertUserGps(model);
	}
	
	public UserGpsModel getUserGpsModel(String userid){
		UserGpsModel model = userGpsModelMap.get(userid);
		if(model == null){
			model = new UserGpsModel(userid);
			userGpsModelMap.put(userid, model);
		}
		return model;
	}
	
	public List<HashMap<String, Object>> getHistoryPoition(HashMap<String, Object> parm){
		List<HashMap<String, Object>> models = dao.getHistoryPoition(parm);
		return models;
	}
	
	/**
	 * 
	 * @作者：罗琦
	 * @param parm
	 * @return
	 */
	public int isUserThere(HashMap<String, String> parm){
		int num = dao.isUserThere(parm);
		return num;
	}
	
	/**
	 * 分别在系统和警务通平台添加用户
	 * @作者：罗琦
	 * @param user
	 * @throws Exception
	 */
	@Transactional(readOnly = false)
	public void register(UserModel user) throws Exception{
		HashMap<String, String> parm = new HashMap<String, String>();
		parm.put("name", user.getUsername());
		int num = isUserThere(parm);
		if(num > 0){
			throw new MessageException("用户名已存在");
		}
		
		List<HashMap<String, Integer>> jwtUserIds = dao.getPersonId(user.getUsername());
		
		if(jwtUserIds.size() >=1){
			throw new MessageException("用户名已存在");
		}
		
		String id = dao.getId();
		user.setId(id);
		user.setImei(user.getUsername());
		user.setImageurl("images/nohead.png");
		dao.insert(user);
		insertUserToJWT(user);
		SessionUnit.setUserId(user.getId() + "");
		SessionUnit.setUserName(user.getShowname());
	}
	
	@Transactional(readOnly = false)
	public void deleteUser(String[] ids, String[] loginnames) throws Exception{
		for(String id : ids){
			UserModel model = new UserModel();
			model.setId(id);
			model.setUpdatedBy(SessionUnit.getUserId());
			model.setStatus("0");
			dao.update(model);
		}
		
		for(String loginname : loginnames){
			UserModel user = new UserModel();
			user.setUsername(loginname);
			try {
				DbManager.beginTransaction();
				deleteUserToJWT(user);
				DbManager.commit();
			} catch (Exception e) {
				DbManager.rollback();
				throw e;
			}
		}
	}
	
	public void deleteUserToJWT(UserModel user) throws Exception{
		
		log.info("开始删除警务通用户数据");
		
		/**获取要删除的人员ID**/
		String sqlGetPersonId = "select p.personid from persons@ysdblink p where p.personcode = ?";
		List<String> getPersonIdparm = new ArrayList<String>();
		getPersonIdparm.add(user.getUsername());
		String personId = DbManager.executeScalar(sqlGetPersonId, getPersonIdparm) + "";
		
		log.info("删除人员与对讲组关系表");
		
		/**删除人员与对讲组关系表**/
		String deleteGroupitemSql = "delete from groupitem@ysdblink where personid = ?";
		List<String> deleteGroupitemparm = new ArrayList<String>();
		deleteGroupitemparm.add(personId);
		DbManager.executeUpdate(deleteGroupitemSql, deleteGroupitemparm);
		
		log.info("删除对讲组中人员权限表");
		
		/**删除对讲组中人员权限表**/
		String deleteGroupcallparameterSql = "delete from groupcallparameter@ysdblink where equipmentcode = ?";
		List<String> deleteGroupcallparameterparm = new ArrayList<String>();
		deleteGroupcallparameterparm.add(user.getUsername());
		DbManager.executeUpdate(deleteGroupcallparameterSql, deleteGroupcallparameterparm);
		
		log.info("删除设备与人员关系表");
		
		/**删除设备与人员关系表**/
		String deleteEquipmentffpersonSql = "delete from equipmentffperson@ysdblink where personid = ?";
		List<String> deleteEquipmentffpersonparm = new ArrayList<String>();
		deleteEquipmentffpersonparm.add(personId);
		DbManager.executeUpdate(deleteEquipmentffpersonSql, deleteEquipmentffpersonparm);
		
		log.info("删除用户使用的设备");
		
		/**删除用户使用的设备**/
		String deleteEquipmentSql = "delete from equipment@ysdblink where imeinum = ?";
		List<String> deleteEquipmentparm = new ArrayList<String>();
		deleteEquipmentparm.add(user.getUsername());
		DbManager.executeUpdate(deleteEquipmentSql, deleteEquipmentparm);
		
		log.info("删除用户表");
		
		/**删除用户表**/
		String deletePersonsSql = "delete from persons@ysdblink where personcode = ?";
		List<String> deletePersonsparm = new ArrayList<String>();
		deletePersonsparm.add(user.getUsername());
		DbManager.executeUpdate(deletePersonsSql, deletePersonsparm);
	}
	
	public void updateApp(UserModel model) throws Exception{
		model.setUsername(null);
		dao.update(model);
		updateUserJWTInfo(model);
	}
	
	public void updateUserJWTInfo(UserModel user) throws Exception{
		log.info("开始更新警务通信息");
		
		UserModel oldModel = getModel(user.getId());
		
		HashMap<String, String> deptGroupMap = dao.getJwtDeptTallgroup(user.getPcs());
		String jwtDeptId = null;
		String tallGroup = null;
		
		if(deptGroupMap != null){
			jwtDeptId = deptGroupMap.get("JWT_DEPTID");
			tallGroup = deptGroupMap.get("TALLGROUPID");
		}
		
		if(jwtDeptId == null || jwtDeptId.equals("")){
			jwtDeptId = "516";
		}
		
		log.info("获取单位对讲组对应关系："+jwtDeptId+","+tallGroup);
		
		/**更新设备表**/
		
		String updateEquipmentSql = "update equipment@ysdblink set departmentid = ? where equipmentcode = ?";
		
		List<String> updateEquipmentparm = new ArrayList<String>();
		updateEquipmentparm.add(jwtDeptId);
		updateEquipmentparm.add(oldModel.getUsername());
		
		DbManager.executeUpdate(updateEquipmentSql, updateEquipmentparm);
		
		/**更新人员表**/
		
		String updatePersonSql = "update persons@ysdblink set name=?,departmentid=? where personcode = ? ";
				
		List<String> updatePersonParm = new ArrayList<String>();
		
		updatePersonParm.add(user.getShowname());
		updatePersonParm.add(jwtDeptId);
		updatePersonParm.add(oldModel.getUsername());
		
		DbManager.executeUpdate(updatePersonSql, updatePersonParm);
		
		String getPersionidSql = " SELECT personid FROM persons@ysdblink where personcode = ? ";
		List<String> getPersonIdParm = new ArrayList<String>();
		getPersonIdParm.add(oldModel.getUsername());
		String personid = DbManager.executeScalar(getPersionidSql, getPersonIdParm)+"";
		
		/**更新设备人员关系表**/
		
		String updateEqPersonSql = "update equipmentffperson@ysdblink set departmentid=? where personid=?";
				
		List<String> parm = new ArrayList<String>();
		parm.add(jwtDeptId);
		parm.add(personid);
		
		DbManager.executeUpdate(updateEqPersonSql, parm);
		
		if(tallGroup != null && !tallGroup.equals("")){
			jwtTallGroupService.insertUserToTallGroup(personid, tallGroup, oldModel.getUsername());
			log.info("更新对讲组");
		}
		
		DbManager.commit();
	}
	
	public void insertUserToJWT(UserModel user) throws Exception{
		
		log.info("开始往警务通里面注册");
		
		/**获取单位对讲组对应关系**/
		HashMap<String, String> deptGroupMap = dao.getJwtDeptTallgroup(user.getPcs());
		String jwtDeptId = null;
		String tallGroup = null;
		
		if(deptGroupMap != null){
			jwtDeptId = deptGroupMap.get("JWT_DEPTID");
			tallGroup = deptGroupMap.get("TALLGROUPID");
		}
		
		if(jwtDeptId == null || jwtDeptId.equals("")){
			jwtDeptId = "516";
		}
		
		String sqlGetEquipId = " SELECT seq_equipment.nextval@ysdblink FROM dual ";
		String equipmentId = DbManager.executeScalar(sqlGetEquipId, null) + "";
		
		log.info("获取单位对讲组对应关系："+jwtDeptId+","+tallGroup);
		
		/**插入设备表**/
		
		String insertEquipmentSql = "insert into equipment@ysdblink(equipmentid,equipmentcode,equipmenttypeid,departmentid,imeinum,mobilephone,storestatuscode,usestatuscode,createtime)"
		 +"values(?,?,?,?,?,?,?,?,sysdate)";
		
		List<String> insertEquipmentparm = new ArrayList<String>();
		insertEquipmentparm.add(equipmentId);
		insertEquipmentparm.add(user.getUsername());
		insertEquipmentparm.add("64");
		insertEquipmentparm.add(jwtDeptId);
		insertEquipmentparm.add(user.getUsername());
		insertEquipmentparm.add(user.getUsername());
		insertEquipmentparm.add("3");
		insertEquipmentparm.add("3");
		
		DbManager.executeUpdate(insertEquipmentSql, insertEquipmentparm);
		
		log.info("插入设备表成功");
		
		/**插入人员表**/
		
		String sqlGetPersionId = " SELECT seq_persons.nextval@ysdblink FROM dual ";
		String persionId = DbManager.executeScalar(sqlGetPersionId, null) + "";
		
		String insertPersonSql = "insert into persons@ysdblink(personid,personcode,name,departmentid,persontypeid,createtime) "
		+" values(?,?,?,?,?,sysdate)";
		
		List<String> insertPersonParm = new ArrayList<String>();
		insertPersonParm.add(persionId);
		insertPersonParm.add(user.getUsername());
		insertPersonParm.add(user.getShowname());
		insertPersonParm.add(jwtDeptId);
		insertPersonParm.add("141");
		
		DbManager.executeUpdate(insertPersonSql, insertPersonParm);
		
		log.info("插入人员表成功");
		
		/**插入设备人员关系表**/
		
		String insertEqPersonSql = "insert into equipmentffperson@ysdblink(id,departmentid,personid,equipmentid,createtime)"
				+" values(seq_equipmentffperson.nextval@ysdblink,?,?,?,sysdate)";
				
		List<String> parm = new ArrayList<String>();
		parm.add(jwtDeptId);
		parm.add(persionId);
		parm.add(equipmentId);
		
		DbManager.executeUpdate(insertEqPersonSql, parm);
		
		log.info("插入设备人员关系表成功");
		
		if(tallGroup != null && !tallGroup.equals("")){
			jwtTallGroupService.insertUserToTallGroup(persionId, tallGroup, user.getTelNumber());
			log.info("插入对讲组");
		}
		
		DbManager.commit();
	}
	
	@Transactional(readOnly = false)
	public void updateUsersLocation(String[] loginnames, String timer) throws Exception{
		for(String loginname : loginnames){
			UserModel user = new UserModel();
			user.setUsername(loginname);
			try {
				DbManager.beginTransaction();
				updateUsersLocationInJWT(user, timer);
				DbManager.commit();
			} catch (Exception e) {
				e.printStackTrace();
				DbManager.rollback();
				throw e;
			}
		}
	}
	
	public void updateUsersLocationInJWT(UserModel user, String timer) throws Exception{
		
		log.info("开始修改用户位置上传的周期");
		
		/**插入指令下发设置表**/
		String insertSendcommandSql = "insert into dgjwt.sendcommand@ysdblink(commandid,commandtype,commandparam,equipmentcode) values(dgjwt.seq_sendcommand.nextval@ysdblink,?,?,?)";
		List<String> parm = new ArrayList<String>();
		parm.add("1");
		parm.add(timer);
		parm.add(user.getUsername());
		
		DbManager.executeUpdate(insertSendcommandSql, parm);
	}
	
	public String updateImageUrl(UserModel model) throws MessageException{
		String path = "";
		try {
			uploadFile(model);
			dao.update(model);
			path = model.getImageurl();
		} catch (Exception e) {
			e.printStackTrace();
			throw new MessageException("头像上传失败", "4");
		}
		return path;
	}
	
	public void update(String id, String pwd){
		UserModel user = new UserModel();
		user.setId(id);
		user.setPassword(pwd);
		dao.update(user);
	}
	
	public int getUserCount(HashMap<String, String> parm){
		int num = dao.getUserCount(parm);
		return num;
	}
	
	public void updatePwd(HashMap<String, String> parm){
		dao.updatePwd(parm);
	}
	
	public void updateUser(String id, String sex, String username, String phone,
			String type, String job, String mjjh, String deptfullid,String carId,String bankcardNo){
		UserModel user = new UserModel();
		user.setId(id);
		user.setSex(sex);
		user.setShowname(username);
		user.setTelNumber(phone);
		user.setUsertype(type);
		user.setUserJob(job);
		user.setDeptfullid(deptfullid);
		user.setMjjh(mjjh);
		user.setCardId(carId);
		user.setBankcardNo(bankcardNo);
		dao.update(user);
	}
	
	@Transactional(readOnly=false)
	public void insert(List<UserModel> list){
		for(int i = 0; i < list.size(); i++){
			UserModel user = list.get(i);
			dao.insert(user);
			System.out.println(user.getId());
			System.out.println(user.getUsername());
			System.out.println(user.getShowname());
			System.out.println(user.getUsertype());
			System.out.println(user.getTelNumber());
		}
	}
	
	public List<HashMap<String, Object>> getUserTeam(String id){
		List<HashMap<String, Object>> team = dao.getUserTeam(id);
		return team;
	}
	
	public List<HashMap<String, Object>> getGroupUsers(String id){
		List<HashMap<String, Object>> team = dao.getGroupUsers(id);
		return team;
	}
	
	public List<HashMap<String, Object>> getgroups(String id){
		UserModel model = getModel(id);
		List<HashMap<String, Object>> team = dao.getgroups(model.getUsername());
		return team;
	}
	
	public String uploadFile(UserModel model) throws Exception{
		
		FileItem item = RequestUnit.getFileItem("img");
		String resultPath = "";
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssS");
		
		if(item!=null)
		{
			String path = WebContext.getRequest().getSession().getServletContext().getInitParameter("UploadPath");
			String dataStr = sf.format(Calendar.getInstance().getTime());
			resultPath = "upload/police/"+FileUpload.saveFile(item, path+"/upload/police/",dataStr+"_"+model.getId());
			log.info(model.getId()+"图片上传成功:"+resultPath);
			model.setImageurl(resultPath);
		}
		else{
			log.info(model.getId()+"没有图片数据");
		}
		return resultPath;
	}
	
	public List<HashMap<String, String>> getUserAppStatisticsChart(){
		List<HashMap<String, String>> list = dao.getUserAppStatistics();
		return list;
	}
	
	public String getUserAppStatisticsGrid(){
		String json = gridDao.selectPage(UserDao.class, null, "getUserAppStatistics");
		return json;
	}
}
